/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import DataAccess.DataAccessFacade;

import DomainModel.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 *
 * @author Mershack/Patrick
 */
@WebServlet(name = "AdminCourseController", urlPatterns = {"/AdminCourseController"})
public class AdminCourseController extends HttpServlet
{

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        //PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("currentUser");

        if (user == null || user.getRole() != Role.ADMIN) {
            request.getRequestDispatcher("/login").forward(request, response);
        }
    }

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">


    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
        processRequest(request, response);

        String action = request.getParameter("action");
        
        if (action != null && action.equals("loadCourses")) {
            doLoadCourses(request, response);
         }
        
        request.getRequestDispatcher("/WEB-INF/grs/adminCoursesView.jsp").forward(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
        processRequest(request, response);

        String actionAddCourse = request.getParameter("addCourse");
        String actionEditCourse = request.getParameter("editCourse");
        String submitDeleteCourse = request.getParameter("submitDeleteCourse");
        String submitCourse = request.getParameter("submitCourse");
        String cancelSubmitCourse = request.getParameter("cancelSubmitCourse");
     

        // ADD course
        if (actionAddCourse != null) {
            request.getRequestDispatcher("/WEB-INF/grs/adminCoursesAdd.jsp").forward(request, response);
        }
        if (actionEditCourse != null) { // EDIT course
            doEditCourse(request, response);
        } 
        if (submitDeleteCourse != null ) {
            doDeleteCourse(request,response);
            request.getRequestDispatcher("/WEB-INF/grs/adminCoursesView.jsp").forward(request, response);
        } else if (cancelSubmitCourse != null) { // CANCEL submitting a course
            request.getRequestDispatcher("/WEB-INF/grs/adminCoursesView.jsp").forward(request, response);
        } else if (submitCourse != null) { // SUBMIT add/edit course
            if (doAddCourse(request, response)) {
                request.getRequestDispatcher("/WEB-INF/grs/adminCoursesView.jsp").forward(request, response);
            } else {
                request.getRequestDispatcher("/WEB-INF/grs/adminCoursesAdd.jsp").forward(request, response);
            }
        }
    }

    protected void doLoadCourses(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
        try {
            DataAccessFacade dataAccessFacade = DataAccessFacade.getInstance();

            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            try {
                List<Course> allCourses = dataAccessFacade.getAllCourses();
                JSONArray allCoursesJson = new JSONArray();
        
                for (Course course : allCourses) {
                    JSONObject courseJson = new JSONObject();

                    courseJson.put("CourseId", course.getCourseId());
                    courseJson.put("CourseName", course.getCourseName());
                    courseJson.put("CourseCode", course.getCourseCode());
                    courseJson.put("CreditHours", course.getCreditHours());
                    

                    allCoursesJson.put(courseJson);
                }
                String allCoursesStr = allCoursesJson.toString();
                out.print(allCoursesStr);

            } catch (Exception e) {
            } finally {
                out.close();
            }
        } catch (Exception e) {
        }
    }

    private void doEditCourse(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
        request.setAttribute("inputCourseId", request.getParameter("inputCourseId"));
        request.setAttribute("inputCourseName", request.getParameter("inputCourseName"));
        request.setAttribute("inputCourseCode", request.getParameter("inputCourseCode")); //needs validity checks
        request.setAttribute("inputCreditHours", request.getParameter("inputCreditHours")); // needs validity checks

        request.getRequestDispatcher("/WEB-INF/grs/adminCoursesAdd.jsp").forward(request, response);
    }

    private boolean doAddCourse(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
        Map<String, String> messages = new HashMap<>();
        request.setAttribute("messages", messages);

        try {
            String strName = request.getParameter("inputCourseName");
            String strCode = request.getParameter("inputCourseCode");
            String strCourseId = request.getParameter("inputCourseId");
            String strHours = request.getParameter("inputCreditHours");
            
            int courseId = (strCourseId == null || strCourseId.isEmpty()) ? 0 : Integer.valueOf(strCourseId);
            int hours = (strHours == null || strHours.isEmpty()) ? 0 : Integer.valueOf(strHours);
            request.setAttribute("inputCourseId", strCourseId);
            request.setAttribute("inputCourseName", strName);
            request.setAttribute("inputCourseCode", strCode); //needs validity checks
            request.setAttribute("inputCreditHours", strHours); // needs validity checks

            Course course = new Course(courseId, strCode, strName, hours);
            String validationResult = course.validate();
            if (!validationResult.isEmpty()) {
                messages.put("error", validationResult);
                return false;
            }

            DataAccessFacade.getInstance().setCourse(course);

            String msg = (courseId == 0) ? "Course added successfully." : "Course edited successfully.";
            messages.put("success", msg);
        } catch (Exception e) {
            messages.put("error", "An error occurred adding the Course.");
            return false;
        }

        return true;
    }

    private void doDeleteCourse(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        String strInputCourseId = request.getParameter("inputCourseId");
        int courseId=  Integer.parseInt(strInputCourseId);
        Map<String, String> messages = new HashMap<>();
        request.setAttribute("messages", messages);
        try { 
            boolean result = DataAccessFacade.getInstance().deleteCourse(courseId);

            if (result) {
                messages.put("success", "Course deleted successfully");
            }
            else {
                messages.put("error", "Could not delete this course.");
            }
        }
        catch (Exception e) {
            messages.put("error", "An error occurred while deleting this course");
        }    
        finally {
            //request.getRequestDispatcher("/WEB-INF/grs/adminCoursesView.jsp").forward(request, response);
        }
    }
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
